import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:xws/helpers/as_t.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/models/notify/jpush_obj.dart';
import 'package:xws/models/user/user_update_obj.dart';
import 'package:xws/state/app_state.dart';
import 'package:xws/state/user_state.dart';
import 'package:xws/ui/home/home_page.dart';
import 'package:xws/ui/mine/mine_page.dart';
import 'package:xws/ui/notify/notify_page.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/dio_utils/request/user_req.dart';
import 'package:xws/utils/loc_util.dart';
import 'package:xws/utils/log_util.dart';
import 'package:xws/utils/push_util.dart';
import 'package:xws/utils/tools_util.dart';
import 'package:xws/widgets/dialog/lv_up.dart';
import 'package:xws/widgets/safe_scaffold.dart';

import 'nav_bar.dart';

class AppRoot extends StatefulWidget {
  const AppRoot({Key? key}) : super(key: key);

  @override
  _AppRootState createState() => _AppRootState();
}

class _AppRootState extends State<AppRoot> with SafeState<AppRoot> {
  late PageController _pageController;

  @override
  void initState() {
    super.initState();
    _init();
    _pageController = PageController();
  }

  @override
  void dispose() {
    _pageController.dispose();
    clearAMap();
    PU.clearHandler();
    super.dispose();
  }

  /// 初始化
  Future<void> _init() async {
    try {
      us.updateBasicInfo();

      await PU.setHandler(
        onOpenNotification: _tapPushToOpenApp,
        onReceiveMessage: (Map<String, dynamic> d) async {
          warning('[onReceiveMessage]');
          apps.changeUnread(1);
        },
      );

      await initJpush();

      final String id = PU.getJPushId();

      if (id.isNotEmpty) {
        updateInfo(UserUpdateObj(registrationId: id));

        PU.onRecive = _dealRecive;
      }

      final Map<dynamic, dynamic>? initMsgData = await PU.getInitMsg();

      if (initMsgData != null && initMsgData.isNotEmpty) {
        _tapPushToOpenApp(Map<String, dynamic>.from(initMsgData));
      }
    } catch (e) {
      error('app初始化出错:$e');
    }
  }

  /// 处理收到的推送消息
  Future<void> _dealRecive(Map<String, dynamic> data) async {
    try {
      final JPushObj jPushObj = JPushObj.fromJson(data);
      final Map<String, dynamic> content = jPushObj.getExtras;
      warning('PU.onRecive $content');

      final bool hasType = content.containsKey('messageType');

      if (hasType) {
        if (content['messageType'] == 'INTEGRAL_CHANGE') {
          PU.cancelJPushNotify(id: jPushObj.notifyId);
          final Map<String, dynamic> cData = asT<Map<String, dynamic>>(json.decode(content['content'].toString()));
          final int oldIntegral = asT<int>(cData['oldIntegral']);
          final int newIntegral = asT<int>(cData['newIntegral']);
          final int diffPoint = newIntegral - oldIntegral;

          if (diffPoint < 0)
            pointToast('积分 $diffPoint');
          else
            pointToast('积分 +$diffPoint');

          final int oldLevel = asT<int>(cData['oldLevel']);
          final int newLevel = asT<int>(cData['newLevel']);
          if (newLevel > oldLevel) {
            customDialog(LvUp(newLevel: newLevel, currPoints: newIntegral));
          }

          us.updateBasicInfo();
        }
      }

      apps.changeUnread(1);
    } catch (e) {
      error('处理推送出错:$e');
    }
  }

  /// 点击推送打开app
  Future<void> _tapPushToOpenApp(Map<String, dynamic> data) async {
    try {
      debug('[PUSH]_tapPushToOpenApp:$data');
      if (data.containsKey('extras')) {
        if (!PU.notifyPageNow) {
          if (isLogin) await push(context, const NotifyPage());
        }
      }
    } catch (e) {
      error('点击推送打开app失败:$e');
    }
  }

  @override
  Widget build(BuildContext context) {
    initToast(context);

    return WillPopScope(
      onWillPop: () async => await exitHold(context),
      child: MediaQuery(
        data: MediaQueryData.fromWindow(window).removePadding(removeBottom: true),
        child: SafeScaffold(
          resizeToAvoidBottomInset: false,
          autoAppBar: false,
          body: PageView(
            controller: _pageController,
            physics: const NeverScrollableScrollPhysics(),
            children: const <Widget>[HomePage(), MinePage()],
          ),
          floatingActionButton: NavBar(onTap: (int index) {
            _pageController.jumpToPage(index);
            if (index == 1) us.updateBasicInfo();
          }),
          floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        ),
      ),
    );
  }
}
